Component({
  data: {
    lottieUrl:'',
    showBluetoothList:  false,
    bluetoothList: [],
    selectedDeviceId: null,
    selectedDeviceName: null,
    showModal: false,
    showNewModal: false,
    isConnecting: false,
    serviceId: null,
    characteristicId: null,
    showSearchingModal: false,
    showSuccessModal: false, // 新增：成功弹窗显隐
    showFailModal: false,     // 新增：失败弹窗显隐
    showWifiConfig: false,
    wifiPasswords: {}
  },
  pageLifetimes:{
    show(){
      
    },
    hide(){

    }
  },
  methods:{
    searchBluetooth() {
      const that = this;
      // 清空设备列表
      that.setData({
        bluetoothList: [],
        selectedDeviceId: null,
        selectedDeviceName: null,
        serviceId: null,
        characteristicId: null
      });
  
      // 初始化蓝牙模块
      wx.openBluetoothAdapter({
        success: () => {
          // 开始搜索附近的蓝牙设备
          wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey:false,//去重
            interval:0,//间隔
            success: () => {
              // 获取已发现的蓝牙设备
              wx.onBluetoothDeviceFound((res) => {
                let newList = that.data.bluetoothList;
                const device = res.devices[0];
                newList.push({
                  name: device.name,
                  deviceId: device.deviceId
                });
                that.setData({
                  bluetoothList: newList,
                  showBluetoothList: true
                });
                // 在控制台输出搜索到的蓝牙列表
                console.log('搜索到的蓝牙列表:', newList);
              });
            },
            fail: (err) => {
              console.error('搜索蓝牙设备失败', err);
            }
          });
        },
        fail: (err) => {
          console.error('初始化蓝牙模块失败', err);
        }
      });
    },
  
    hideBluetoothList() {
      this.setData({
        showBluetoothList: false,
        selectedDeviceName: null,
        serviceId: null,
        characteristicId: null
      });
      // 停止搜索蓝牙设备
      wx.stopBluetoothDevicesDiscovery({
        success: () => {
          console.log('停止搜索蓝牙设备');
        },
        fail: (err) => {
          console.error('停止搜索蓝牙设备失败', err);
        }
      });
    },
  
    selectDevice(e) {
      const { deviceId, deviceName } = e.currentTarget.dataset;
      this.setData({
        selectedDeviceId: deviceId,
        selectedDeviceName: deviceName
      });
      wx.showModal({
        title: '选择蓝牙设备: '+deviceName+'(ID:'+deviceId+')',
      })
    },
  
    connectAndHide() {
      const { selectedDeviceId, selectedDeviceName } = this.data;
      if (!selectedDeviceId) {
        console.error('未选择蓝牙设备');
        return;
      }
      this.setData({
        isConnecting: true,
        showSearchingModal: true // 开始连接时显示弹窗
      });
      this.animationTimer = null;
      this.initCanvas()
      console.log(`尝试连接蓝牙设备: ${selectedDeviceName} (ID: ${selectedDeviceId})`);
      // 这里添加实际的蓝牙连接逻辑
      wx.createBLEConnection({
        deviceId: selectedDeviceId,
        success: () => {
          getApp().globalData.status=1
          // 获取设备的服务
          wx.getBLEDeviceServices({
            deviceId: selectedDeviceId,
            success: (res) => {
              console.log('获取设备服务成功', res.services);
              if (res.services.length > 0) {
                const serviceId = res.services[0].uuid;
                this.setData({ serviceId });
                // 获取设备的特征值
                wx.getBLEDeviceCharacteristics({
                  deviceId: selectedDeviceId,
                  serviceId: serviceId,
                  success: (res) => {
                    console.log('获取设备特征值成功', res.characteristics);
                    if (res.characteristics.length > 0) {
                      const characteristicId = res.characteristics[0].uuid;
                      this.setData({ characteristicId });
                      
                      console.log('获取到的 serviceId:', serviceId, 'characteristicId:', characteristicId);
                
                    }
                  },
                  fail: (err) => {
                    console.error('获取设备特征值失败', err);
                  }
                });
              }
            },
            fail: (err) => {
              console.error('获取设备服务失败', err);
            }
          });
          // 连接成功，4秒后隐藏搜索弹窗并显示成功弹窗
            this.setData({
              showSearchingModal: false,
              showSuccessModal: true
            });
            if (this.animationTimer) {
              clearTimeout(this.animationTimer);
              this.animationTimer = null;
            }
            // 成功弹窗显示一段时间后隐藏
            setTimeout(() => {
              this.setData({ 
                showSuccessModal: false,
                showWifiConfig:true
               });
            }, 2000);
        },
        fail: (err) => {
          console.error('蓝牙连接失败', err);
  
            this.setData({
              showSearchingModal: false,
              showFailModal: true
            });
            //清理动画
            if (this.animationTimer) {
              clearTimeout(this.animationTimer);
              this.animationTimer = null;
            }
        },
        complete: () => {
          this.setData({
            isConnecting: false,
            showBluetoothList: false,
            selectedDeviceName: null
          });
          // 停止搜索蓝牙设备
          wx.stopBluetoothDevicesDiscovery({
            success: () => {
              console.log('停止搜索蓝牙设备');
            },
            fail: (err) => {
              console.error('停止搜索蓝牙设备失败', err);
            }
          });
        }
      });
    },
    // 显示登录弹窗
    showLoginModal() {
      this.setData({
        showModal: true
      });
    },
  
    // 隐藏登录弹窗
    hideModal() {
      this.setData({
        showModal: false
      });
    },
  
    // 一键授权登录，显示连接蓝牙前检查弹窗
    oneKeyLogin() {
      this.setData({
        showModal: false,
        showNewModal: true
      });
    },
  
    // 开始连接，执行搜索蓝牙列表方法
    startConnect() {
      this.setData({
        showNewModal: false,
        showFailModal:false
      });
          // 停止搜索蓝牙设备
          wx.stopBluetoothDevicesDiscovery({

          });
      this.searchBluetooth();
    },
  
    // 隐藏连接蓝牙前检查弹窗
    hideNewModal() {
      this.setData({
        showNewModal: false
      });
    },
    
      // 连接成功回调
      onConnectSuccess() {
        getApp().globalData.status=1
      },
      
      // 连接失败回调
      onConnectFail() {
        getApp().globalData.status=0
      },
  
      // 修改切换底部栏方法
      switchToHome() {
        const pages = getCurrentPages();
        this.setData({ showBluetoothList: false }); // 新增隐藏逻辑
        
        const homePage = pages.find(page => page.route === 'pages/home/home');
        if (homePage) {
          homePage.setData({ connectionStatus: 1 });
          wx.navigateBack();
        }
      },
      // 移除原有的hideBluetoothList方法
      searchWifi() {
        wx.showLoading({ title: '搜索中...' })
        wx.startWifi({
          allowDuplicatesKey:false,
          success: () => {
            wx.getWifiList({
              success: (res) => {
                wx.onGetWifiList((result) => {
                  const uniqueWifi = result.wifiList.reduce((acc, current) => {
                    const existing = acc.find(item => item.SSID === current.SSID);
                    if (!existing) {
                      acc.push(current);
                    } else if (current.RSSI > existing.RSSI) { // 比较信号强度
                      acc[acc.indexOf(existing)] = current;
                    }
                    return acc;
                  }, []);
                  
                  this.setData({
                    wifiList: uniqueWifi.map(item => ({
                      ssid: item.SSID,
                      strength: item.RSSI
                    }))
                  });
                })
                wx.hideLoading()
              }
            })
          }
        })
      },
    
      hideWifiConfig: function() {
        this.setData({ showWifiConfig: false });
      },
    
      selectWifi: function(e) {
        const deviceId = this.data.connectedDeviceId;
        const ssid = e.currentTarget.dataset.ssid;
        const password = ''; // 需要添加密码输入逻辑
    
        // 构建蓝牙数据包（示例协议）
        const buffer = new ArrayBuffer(64);
        const dataView = new DataView(buffer);
        const encoder = new TextEncoder();
        encoder.encodeInto(`WIFI:${ssid},${password}`, new Uint8Array(buffer));
    
        // 发送蓝牙数据
        wx.writeBLECharacteristicValue({
          deviceId,
          serviceId: this.data.serviceId,
          characteristicId: this.data.writeCharId,
          value: buffer,
          success: () => console.log('WiFi配置发送成功')
        });
      },
      updatePassword: function(e) {
        const ssid = e.currentTarget.dataset.ssid;
        this.setData({
          [`wifiPasswords.${ssid}`]: e.detail.value
        });
      },

          // 新增通过蓝牙发送数据的方法
    sendDataViaBluetooth: function () {
      const { selectedDeviceId, serviceId, characteristicId } = this.data;
      let data='11111111'
      // if (!selectedDeviceId) {
      //   console.error('未选择蓝牙设备，无法发送数据');
      //   return;
      // }
      // if (!serviceId || !characteristicId) {
      //   console.error('未获取到有效的 serviceId 或 characteristicId，无法发送数据');
      //   return;
      // }
  
      // 将字符串数据转换为 ArrayBuffer
      const buffer = new ArrayBuffer(data.length);
      const dataView = new DataView(buffer);
      for (let i = 0; i < data.length; i++) {
        dataView.setUint8(i, data.charCodeAt(i));
      }
      //console.log('设备ID:', dataView);
      setTimeout(() => {
        wx.writeBLECharacteristicValue({
          deviceId: selectedDeviceId,
          serviceId: serviceId,
          characteristicId: characteristicId,
          value: buffer,
          success: () => {
            console.log('数据发送成功');
            this.setData({ showSuccessModal: true }); // 显示成功弹窗
            setTimeout(() => {
              this.switchToHome()
            }, 2000);
          },
          fail: (err) => {
            console.error('数据发送失败', err);
            this.setData({ showFailModal: true }); // 显示失败弹窗
            setTimeout(() => {
              this.switchToHome()
            }, 2000);
          }
        });
      }, 2000);
    },
// 连接按钮处理
connectWifi: function(data) {
  const ssid = e.currentTarget.dataset.ssid;
  const password = this.data.wifiPasswords[ssid] || '';
  
  // 构建蓝牙数据包
  const buffer = new ArrayBuffer(128);
  const encoder = new TextEncoder();
  encoder.encodeInto(`CONFIG_WIFI:${ssid},${password}`, new Uint8Array(buffer));

  // 发送蓝牙指令
  wx.writeBLECharacteristicValue({
    deviceId: this.data.connectedDeviceId,
    serviceId: this.data.serviceId,
    characteristicId: this.data.writeCharId,
    value: buffer,
    success: () => {
      this.setData({ showWifiConfig: false });
      this.setData({ showSuccessModal: true }); // 显示失败弹窗
      setTimeout(() => {
        this.setData({ showSuccessModal: false }); // 2秒后隐藏
        this.switchToHome()
      }, 2000);
    },
    fail:()=>{
      this.setData({ showWifiConfig: false });
      this.setData({ showFailModal: true }); // 显示失败弹窗
      setTimeout(() => {
        this.setData({ showFailModal: false }); // 2秒后隐藏
        this.switchToHome()
      }, 2000);
    }
  });
},

initCanvas() {
  this.createSelectorQuery()
    .select('#loadingCanvas')
    .fields({node:true,size:true})
    .exec((res) => {
      const canvas = res[0].node;
      const ctx = canvas.getContext('2d');
      const dpr = wx.getSystemInfoSync().pixelRatio;
      canvas.width = 200 * dpr;
      canvas.height = 200 * dpr;
      ctx.scale(dpr, dpr);
      
      this.animate(canvas, ctx);
    });
},

animate(canvas, ctx) {
  let rotation = 0;
  let outerRadius = 60;
  let lastUpdate = Date.now(); // 新增时间戳记录
  let flag=true
  const colors = ['#0782f5'];
  
  const draw = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 原有圆边框
    ctx.beginPath();
    ctx.arc(100, 100, 50, 0, Math.PI * 2); // 95px半径留出边距
    ctx.strokeStyle = '#0782f5';
    ctx.lineWidth = 4;
    ctx.stroke();
    
    // 新增渐隐外圆边
    ctx.save();
    ctx.beginPath();
    ctx.arc(100, 100, outerRadius, 0, Math.PI * 2);
    ctx.strokeStyle = `rgba(150, 200, 245, ${1 - outerRadius/100})`; // 透明度递减
    ctx.lineWidth = 6;
    ctx.stroke();
    ctx.restore();
    
    outerRadius += 1;
    // 新增间隔控制逻辑
    if(outerRadius >= 100) { 
      outerRadius=100
      if(flag) lastUpdate = Date.now();
      flag=false
      // 更新外圆参数
      if(Date.now() - lastUpdate > 300){
        outerRadius = 60;
        flag=true
      } 
    }
    
    ctx.save();
    ctx.translate(100, 100);
    ctx.rotate(rotation * Math.PI / 180);
    
    for(let i = 0; i < 8; i++) {
      ctx.fillStyle = colors[i % colors.length];
      ctx.fillRect(-2, -25, 5, 13);
      ctx.rotate(45 * Math.PI / 180);
    }
    
    ctx.restore();
    rotation = (rotation + 6) % 360;
    this.animationTimer = setTimeout(draw, 16);
  };
  
  draw();
},
  },
})
